package com.dark;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;


/**
 * Created by tengxue on 16-6-21.
 */
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public class TransactionRedisDemo extends AbstractJUnit4SpringContextTests {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void testAddString() throws Exception{
        stringRedisTemplate.opsForValue().set("a","1");
        stringRedisTemplate.opsForValue().set("b","2");

        /**
         * 在连接池环境中，需要借助sessionCallback来绑定connection
         */
        SessionCallback<String> sessionCallback = new SessionCallback<String>() {
            public String execute(RedisOperations operations) throws DataAccessException {
                //这里开始做事务处理
                operations.multi();
                stringRedisTemplate.opsForValue().set("a","abc");
                stringRedisTemplate.opsForValue().set("b","abc");
                operations.exec();
                return "success";
            }
        };
        stringRedisTemplate.execute(sessionCallback);
    }

    @Test
    public void testGetString() throws Exception{
        System.out.println("final the result a is : " + stringRedisTemplate.opsForValue().get("a"));
        System.out.println("final the result b is : "+stringRedisTemplate.opsForValue().get("b"));

    }
}
